package com.hogocloud.corelibrary.common.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.WindowManager
import com.hogocloud.corelibrary.LibConfig
import com.hogocloud.corelibrary.R
import com.hogocloud.corelibrary.utils.DeviceUtils

/**
 * 自定义Dialog基类
 *
 * @author wangheng
 */
abstract class AbsDialog : Dialog {

    private val cancelable: Boolean = false
    private var mHeight: Int = 0
    private var mWidth: Int = 0

    constructor(context: Context) : super(context, R.style.DialogStyle) {
        setCancelable(cancelable)
        initDialog(context)
    }

    protected constructor(context: Context, cancelable: Boolean) : super(context, R.style.DialogStyle) {
        setCancelable(cancelable)

        initDialog(context)
    }

    protected constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener
    ) : super(context, R.style.DialogStyle) {
        setCancelable(cancelable)
        setOnCancelListener(cancelListener)

        initDialog(context)
    }

    private fun initDialog(context: Context) {

    }

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        val window = window
        if (window != null) {

            if (window.decorView != null) {
                window.decorView.setPadding(0, 0, 0, 0)
            }

            val lp = window.attributes
            window.setGravity(Gravity.CENTER)

            mWidth = (DeviceUtils.getScreenWidth(LibConfig.getAppContext()) * 0.8).toInt()

            lp.width = mWidth // 宽度
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT // 高度

            window.attributes = lp
        }
        this.setCancelable(cancelable)
    }

    override fun show() {
        if (isShowing) {
            return
        }
        super.show()
    }

    override fun dismiss() {
        if (!isShowing) {
            return
        }
        super.dismiss()
    }

    fun setDialogSize(height: Int, width: Int) {
        mHeight = height
        mWidth = width
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }
}
